package com.cloudwise.shiro;

import com.cloudwise.entity.User;
import com.cloudwise.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author ：Teacher陈
 * @date ：Created in 2020/12/16 16:40
 * @description：shiro安全框架realm
 * @modified By：
 * @version: 1.0
 */
public class MyRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;

    /**
     * shiro安全框架的认证,
     *
     * @param token
     * @return AuthenticationInfo  ，假如返回的是null就说明认证失败
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("认证开始");
        //开始校验用户名和密码
        //取出令牌信息
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        //登录验证分两个步骤，步骤一查询用户是否存在
        String username = usernamePasswordToken.getUsername();
        User user = userService.queryByUsername(username);
        if (null == user) {
            return null;
        }
        //步骤二，查询密码是否正确
        //数据库中的密码
        String password = user.getPassword();
        //Object principal, Object credentials, String realmName
        /**
         *  * @param principal         the 'primary' principal associated with the specified realm.
         *      * @param hashedCredentials the hashed credentials that verify the given principal.
         *      * @param credentialsSalt   the salt used when hashing the given hashedCredentials
         *      * @param realmName         the realm from where the principal and credentials were acquired.
         */
        String salt = user.getSalt();
        ByteSource byteSource = ByteSource.Util.bytes(salt);
        //自动调用密码比较器，如果能够比较成功，继续走，否则抛出异常
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user, password, byteSource, getName());
        return simpleAuthenticationInfo;
    }

    /**
     * @create by: Teacher陈
     * @description: 授权方法，暂时未使用
     * @create time: 2020/12/17 10:28
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }
}
